import { Form, FormInstance, message, ModalProps } from "antd";

import { useState } from "react";
export interface AntdModalProps {
  form: FormInstance;
  refresh: (payload?:any) => any;
  openModal: any;
  closeModal: any;
  payload: any;
  // assertSuccess: (res: any, msg?: string) => Promise<unknown>,
  modalProps: ModalProps;
  confirmLoading: (flag: boolean) => any;
  [key: string]: any;
}

type ModalConfigProps = Omit<ModalProps, "visible">;

const isNullOrFalse = (v: any) => {
  return v === false || v === null;
};

function useAntdModal<T>(params?: {
  form?: boolean | null;
  refresh?: (payload?:any) => any;
}): AntdModalProps {
  let [form] = Form.useForm();
  let [visible, setVisible] = useState(false);
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
  let [payload, setPayload] = useState<T>({} as T);
  let [modalConfig, setModalConfig] = useState<ModalConfigProps>({});

  const openModal = (payload?: T, modalConfig?: ModalConfigProps) => {
    setVisible(true);
    if (!isNullOrFalse(params?.form)) {
      form.resetFields();
      form.setFieldsValue(payload);
    }
    setPayload(payload as T);
    setModalConfig({ ...modalConfig });
  };
  const closeModal = (_form: FormInstance | any) => {
    setVisible(false);
    if (_form) {
      _form.resetFields && _form.resetFields()
    }
    
    // if (!isNullOrFalse(params?.form)) {
    //   _form?.resetFields ? _form.resetFields() : form.resetFields();
    // }
  };
  // const assertSuccess = (res: any, msg: string = '保存成功') => {

  //     return new Promise((resolve, reject) => {
  //         if (res && res.code == 200) {
  //             resolve({})
  //             message.success(msg)
  //         } else {
  //             reject()
  //         }
  //     })

  // }
  return {
    form,
    closeModal,
    refresh: params?.refresh
      ? params?.refresh
      : () => alert("没有传入刷新方法"),
    // assertSuccess,
    updateModal: (_modalConfig: ModalConfigProps) =>
      setModalConfig({ ...modalConfig, ..._modalConfig }),
    confirmLoading: (loading: boolean) =>
      setModalConfig({ ...modalConfig, confirmLoading: loading }),
    openModal,
    payload,
    modalProps: {
      onOk: closeModal,
      onCancel: closeModal,
      // maskClosable:false,
      // onClose: closeModal,
      ...modalConfig,
      // visible,
      open: visible,
      // visible:visible,
    },
  };
}
export default useAntdModal;
